//创建好友对话相关的小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqChatHistory, reqSendMessage } from '@/api/messages/index'
//引入数据类型
import type {
    friend,
    chatHistoryResponseData,
    conversation,
    messageFormData,
} from '@/api/messages/type'
//引入用户小仓库数据的ts类型
import type { MessagesState } from './types/type'
//引入操作本地存储的工具方法
import { GET_CHAT, SET_CHAT } from '@/utils/chathistory'
import type { responseData } from '@/api/user/type'
import { GET_CHATTINGFRIEND, GET_CONTACTSFRIEND } from '@/utils/friends'

//创建聊天消息小仓库
const useMessagesStore = defineStore('Messages', {
    //小仓库存储数据
    state: (): MessagesState => {
        return {
            conversations: GET_CHAT() as unknown as conversation[],
            chattingFriend: GET_CHATTINGFRIEND() as unknown as friend, //正在与用户聊天的好友
            contactsFriend: GET_CONTACTSFRIEND() as unknown as friend, //通讯录当前展示的好友
            currentAudio: null, //用户正在播放的语音实例
            audioUrl: null, //语音的路径
            selectedFile: null, // 用户添加的文件
        }
    },
    //异步、逻辑
    actions: {
        //用户获取聊天信息的方法
        async getChatHistory() {
            const result: chatHistoryResponseData = await reqChatHistory()
            //成功
            if (result.code == 200) {
                //保证当前async函数返回一个成功的promise
                this.conversations = result.data
                //本地永久化储存一份
                SET_CHAT(result.data)
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },

        //发送聊天消息的方法
        async sendMessage(data: messageFormData) {
            const result: responseData = await reqSendMessage(data)
            //成功
            if (result.code === 200) {
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
    },
    getters: {},
})

//对外暴露获取小仓库的方法
export default useMessagesStore
